/* component */
// @ts-ignore
import CountDown from 'vant/lib/count-down'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
/* entity */
import Field from '@model/entity/Field'
/* hooks */
import { useDialog } from '@hooks/useDialog'
import { UpdateFormDataType, useForm } from '@hooks/form/useForm'
import { useFetchWeiXinApplyTrailFeatureApply, useFetchWeiXinApplyTrailFeatureSendSmsCode, WeiXinApplyTrailFeatureDialogForm } from '@src/modules/system/frame/component/WeiXinApplyTrailFeature/hooks/useWeiXinApplyTrailFeature'
/* model */
import { WeiXinApplyTrailFeatureFormFields } from '@src/modules/system/frame/component/WeiXinApplyTrailFeature/model'
/* scss */
import '@src/modules/system/frame/component/WeiXinApplyTrailFeature/WeiXinApplyTrailFeature.scss'
/* util */
import { PHONE_REG } from '@src/util/validator'
import Log from '@src/util/log'
import { findComponentDownward } from '@src/util/assist'
import { setRootWindowInitData, getRootWindowInitData } from '@src/util/window'
import platform from '@src/util/platform'
import { isString } from '@src/util/type'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, ComputedRef, defineComponent, Ref, ref } from 'vue'
import { CreateElement } from 'vue'

const rootWindowInitData = getRootWindowInitData()

interface WeiXinApplyTrailFeatureDialogPropsSetupState {
  // 表单数据
  form: Ref<WeiXinApplyTrailFeatureDialogForm>;
  FormBuilderComponent: Record<string, any>;
  // 是否正在计时
  isCounting: Ref<boolean>;
  // 是否显示弹窗
  visible: Ref<boolean>;
  // 隐藏弹窗
  hideDialog: VoidFunction
  // 显示弹窗方法
  handlerShowDialog: VoidFunction;
  // 停止计时事件
  // handlerFinishCounting: VoidFunction;
  // // 点击发送验证码事件
  // handlerClickSendCode: VoidFunction;
  // // 点击确定事件
  // handlerClickConfirm: VoidFunction;
  // // 点击取消事件
  // handlerClickCancel: VoidFunction;
  // 更新表单数据
  updateForm: (data: UpdateFormDataType) => void
}

enum WeiXinApplyTrailFeatureDialogEventEnum {
  Close = 'close'
}

export type WeiXinApplyTrailFeatureDialogProps = {}
export type WeiXinApplyTrailFeatureDialogInstance = ComponentInstance & WeiXinApplyTrailFeatureDialogPropsSetupState
export type WeiXinApplyTrailFeatureDialogVM = ComponentRenderProxy<WeiXinApplyTrailFeatureDialogProps> & WeiXinApplyTrailFeatureDialogInstance

const ServiceNumber: string = '400-882-8865'
const IS_NUMBER_REG: RegExp = /^\d{1,}$/

export default defineComponent({
  name: ComponentNameEnum.WeiXinApplyTrailFeatureDialog,
  components: {
    CountDown,
    [CountDown.name]: CountDown
  },
  setup(props: WeiXinApplyTrailFeatureDialogProps, { emit }) {
    
    const { visible, showDialog, hideDialog } = useDialog()
    const { form, resetForm, updateForm } = useForm<WeiXinApplyTrailFeatureDialogForm>(WeiXinApplyTrailFeatureFormFields, {}, emit)
    
    const FormBuilderComponent: Ref<Record<string, any> | null> = ref(null)
    const isCounting: Ref<boolean> = ref(false)
    
    function stopCounting() {
      isCounting.value = false
    }
    
    function startCounting() {
      isCounting.value = true
    }
    
    const getPhoneItemComponent = () => {
      try {
        const FormPhoneComponent = findComponentDownward(FormBuilderComponent.value, 'form-phone')
        return FormPhoneComponent?.$parent
      } catch (error) {
        Log.error(error)
        return null
      }
    }
    
    const validatePhone = () => {
      const phoneItemComponent = getPhoneItemComponent()
      if (!phoneItemComponent) return Promise.resolve(true)
      
      return phoneItemComponent.validate()
    }
    
    const handlerClickSendCode = async () => {      
      const isValidatedPhone = await validatePhone()
      if (isString(isValidatedPhone)) return
      
      // 开始计时
      startCounting()
      // 发送验证码
      const { isSuccess } = await useFetchWeiXinApplyTrailFeatureSendSmsCode(form.value.phone)
      if (!isSuccess) {
        stopCounting()
      }
    }
    
    const handlerFinishCounting = () => {
      // 停止计时
      stopCounting()
    }
    
    function handlerShowDialog() {
      stopCounting()
      resetForm()
      showDialog()
    }
    
    return {
      form,
      isCounting,
      visible,
      FormBuilderComponent,
      hideDialog,
      handlerShowDialog,
      handlerClickSendCode,
      handlerFinishCounting,
      updateForm,
    }
  },
  methods: {
    handlerClickCancel() {
      this.hideDialog()
    },
    handlerClickConfirm() {
      this.FormBuilderComponent?.validate().then(async (valid: boolean) => {
        if (!valid) return
        
        const { isSuccess } = await useFetchWeiXinApplyTrailFeatureApply(this.form as WeiXinApplyTrailFeatureDialogForm)
        
        if (!isSuccess) return
        
        platform.alert('申请成功')
        
        rootWindowInitData.scrm = true
        setRootWindowInitData(rootWindowInitData)
        localStorage.setItem('im_isOpen', '1')
        
        this.$emit(WeiXinApplyTrailFeatureDialogEventEnum.Close)
        
        this.hideDialog()
        
        window.location.reload()
      })
    }
  },
  render(h: CreateElement) {
    
    const phoneValidateRule = function (value: string, field: Field, changeStatus: Function) {
      changeStatus(true)
      return new Promise((resolve, reject) => {
        changeStatus(false)
        if(value == null || !value.toString().length) return resolve(`请输入${field.displayName}`)
        if (![PHONE_REG].some(reg => reg.test(value))) return resolve('请输入正确的电话或者手机号')
        resolve(null)
      })
    }
    
    const handlerOnUpdateCode = (data: UpdateFormDataType) => {
      let { newValue } = data
      
      if (!IS_NUMBER_REG.test(newValue as unknown as string)) {
        data.newValue = '' as unknown as Record<string, any>
      }
      
      this.updateForm(data)
    }
    
    const phoneSlots = (props: { field: Field }) => {
      const { field } = props
      return (
        <form-item validation={phoneValidateRule} label={field.displayName}>
          <form-phone field={field} value={this.form.phone} onUpdate={this.updateForm} />
        </form-item>
      )
    }
    
    const codeSlots = (props: { field: Field }) => {
      const { field } = props
      return (
        <form-item label={field.displayName} validation>
          <div class="wei-xin-apply-trail-feature-dialog-code-item">
            <form-text is-not-input-zh is-only-number field={field} value={this.form.code} onUpdate={handlerOnUpdateCode} />
            {this.isCounting ? (
              <div class="count-text wei-xin-apply-trail-feature-dialog-code-text">
                <van-count-down ref="countDown" time="60000" auto-start format="ss" onFinish={this.handlerFinishCounting} />s后重新发送
              </div>
            ) : (
              <span 
                type="button" 
                class="wei-xin-apply-trail-feature-dialog-code-text wei-xin-apply-trail-feature-dialog-code-btn" 
                onClick={this.handlerClickSendCode}
              >
                获取验证码
              </span>
            )}
          </div>
        </form-item>
      )
    }
    
    return (
      <div>
        <base-modal append-to-body show={this.visible} width="520px" class="wei-xin-apply-trail-feature-dialog-modal">
          
          <div class="wei-xin-apply-trail-feature-dialog-header">
            <div class="wei-xin-apply-trail-feature-dialog-header-title">
              企业版专属功能试用申请
              <i class="iconfont icon-close" onClick={this.handlerClickCancel}></i>
            </div>
            <div class="wei-xin-apply-trail-feature-dialog-header-sub-title">
              为了更好的协助您体验企业版专属功能
              <br />
              请留下您的联系电话
            </div>
          </div>
          
          <div class="wei-xin-apply-trail-feature-dialog-form">
            {this.visible && (
              <form-builder
                ref='FormBuilderComponent'
                fields={WeiXinApplyTrailFeatureFormFields} 
                value={this.form}
                onUpdate={this.updateForm}
                scopedSlots={{
                  phone: phoneSlots,
                  code: codeSlots
                }}
              >
              </form-builder>
            )}
          </div>
          
          <div class="wei-xin-apply-trail-feature-dialog-phone">
            客服电话:{ServiceNumber}
          </div>
          
          <div slot='footer' class='wei-xin-apply-trail-feature-dialog-footer'>
            <el-button onClick={this.handlerClickCancel}>
              取 消
            </el-button>
            <el-button type='primary' onClick={this.handlerClickConfirm}>
              确 定
            </el-button>
          </div>
          
        </base-modal>
      </div>
    )
  }
})
